package com.gulimall.product.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.google.common.collect.Collections2;
import com.gulimall.product.entity.AttrEntity;
import com.gulimall.product.service.AttrService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gulimall.common.utils.PageUtils;
import com.gulimall.common.utils.Query;

import com.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.gulimall.product.service.AttrAttrgroupRelationService;


@Service("attrAttrgroupRelationService")
public class AttrAttrgroupRelationServiceImpl extends ServiceImpl<AttrAttrgroupRelationDao, AttrAttrgroupRelationEntity> implements AttrAttrgroupRelationService {

    @Autowired
    AttrAttrgroupRelationDao relationDao;

    @Autowired
    AttrService attrService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrAttrgroupRelationEntity> page = this.page(
                new Query<AttrAttrgroupRelationEntity>().getPage(params),
                new QueryWrapper<AttrAttrgroupRelationEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public AttrAttrgroupRelationEntity getByAttrId(Long attrId) {
        QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attr_id", attrId);
        AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(queryWrapper);
        return relationEntity;
    }

    @Override
    public List<AttrEntity> getRelaotionAttrs(Long attrgroupId) {
        QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attr_group_id", attrgroupId);
        List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(queryWrapper);
        List<Long> attrIds = relationEntities.stream().map(relation -> {
            return relation.getAttrId();
        }).collect(Collectors.toList());

        List<AttrEntity> attrEntities = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(attrIds)) {
            attrEntities = (List<AttrEntity>) attrService.listByIds(attrIds);
        }
        return attrEntities;
    }

    @Override
    public void deleteRelations(List<AttrAttrgroupRelationEntity> relationEntities) {

        relationDao.deleteBatchRelations(relationEntities);
    }

}